from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from flask import session
from sqlalchemy import not_

from info import constants
from info import db
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue


@profile_blue.route('/user_news_list')
@user_login_data
def user_news_list():
    """
    完成用户自己发布新闻的信息展示，get请求，前台返回页数，后台查询相关数据渲染模板即可
    :return:
    """
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    data = {
        'current_page':current_page,
        'total_page':total_page,
        'user_news':news_list
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blue.route('/diy_news', methods=['POST', 'GET'])
@user_login_data
def user_diy_news():
    if request.method == 'GET':
        """展示个人新闻发布页面
            新闻类型的渲染"""
        categories = Category.query.filter(not_(Category.id == 1)).all()
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        data = {
            'categories':category_list
        }
        return render_template('news/user_news_release.html', data=data)
    """
        接下来开始获取相应的数据，然后添加到数据库中
    """
    title = request.form.get("title")
    category = request.form.get('category')
    digest = request.form.get('digest')
    content = request.form.get('content')
    source = '个人新闻'
    if not all([title, category, digest, content]):
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    # 1. 获取到上传的文件
    try:
        avatar_file = request.files.get("image").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2. 再将文件上传到七牛云
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 将头像信息更新到当前用户的模型中
    # 设置新闻模型，添加属性
    news = News()
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + url
    # news.index_image_url = url
    news.title = title
    news.category_id = category
    news.digest = digest
    news.source = source
    news.content = content
    news.user_id = g.user.id
    # 将数据保存到数据库
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")
    # 4. 返回上传的结果<avatar_url>
    return jsonify(errno=RET.OK, errmsg="新闻发布成功，正在审核中")


@profile_blue.route('/collection')
@user_login_data
def user_collect():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_list = []
    for news in collections:
        collection_dict_list.append(news.to_basic_dict())

    data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_list}
    return render_template('news/user_collection.html', data=data)


@profile_blue.route("/pass_change", methods=['POST', 'GET'])
@user_login_data
def password_change():
    if request.method == 'GET':
        return render_template("news/user_pass_info.html")
    # 1. 获取到传入参数
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息
    user = g.user

    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 更新数据
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="密码修改成功")
    # print('success')
    # return 'hello python'


@profile_blue.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

    # 1. 获取到上传的文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2. 再将文件上传到七牛云
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 将头像信息更新到当前用户的模型中

    # 设置用户模型相关数据
    user.avatar_url = url
    # 将数据保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    # 4. 返回上传的结果<avatar_url>
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@profile_blue.route("/user_info", methods=["POST", "GET"])
@user_login_data
def user_base_info():
    """
    实现个人页面显示和修改用户昵称，签名和性别等信息的逻辑
    :return:
    """
    user = g.user
    if request.method == "GET":
        data = {
            "user":user.to_dict() if user else None
        }
        return render_template("news/user_base_info.html", data=data)

    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    # 前端已经对nick_name, gender进行了判空处理
    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    if gender not in(['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 更新并保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name
    # 4. 返回响应
    # return jsonify(errno=RET.OK, errmsg="更新成功")
    # print('success')
    return 'success'


@profile_blue.route("/user")
@user_login_data
def user():
    data = {
        "user":g.user.to_dict() if g.user else None
    }
    return render_template("news/user.html", data=data)
